package com.yuerlive.paperplane.database;

import android.arch.persistence.room.Room;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by Admin on 2017/10/13.
 */

public class DatabaseCreator {
    @Nullable
    private static DatabaseCreator instance=null;

    private AppDatabase mDb;

    private final AtomicBoolean mInitializing =new AtomicBoolean(true);

    private final AtomicBoolean mIsDbCreated =new AtomicBoolean(false);

    private static final Object LOCK =new Object();

     public synchronized static DatabaseCreator getInstance(){
         if(instance==null){
             synchronized (LOCK){
                 if(instance==null){
                     instance=new DatabaseCreator();
                 }
             }
         }
         return  instance;
     }
     public void createDb(Context context){
         Log.d("DatabaseCreator", "Creating DB from " + Thread.currentThread().getName());
         if(!mInitializing.compareAndSet(true,false)){
             return;
         }
         new AsyncTask<Context,Void,Void>(){
             @Override
             protected void onPostExecute(Void aVoid) {
                 super.onPostExecute(aVoid);
                 mIsDbCreated.set(true);
             }

             @Override
             protected Void doInBackground(Context... params) {
                 Context ctx =params[0].getApplicationContext();
                 mDb = Room.databaseBuilder(ctx,AppDatabase.class,AppDatabase.DATABASE_NAME).build();
                 return null;
             }
         }.execute(context.getApplicationContext());
     }


     public boolean isDatabaseCreated(){
         return  mIsDbCreated.get();
     }
     @Nullable
    public AppDatabase getDatabase(){
         return  mDb;
     }

}
